package algorithm.leetcode.I1to100;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Q15 {

    public List<List<Integer>> threeSum(int[] nums) {

        List<List<Integer>> result = new LinkedList<>();

        // 升序排列
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 2; i++) {
            // 这里控制重复答案(之一),这里不会漏掉解,因为num[i]可能的解已经被num[i-1]的时候枚举过了
            if (i > 0 && nums[i] == nums[i - 1]) continue;

            int j = i + 1, k = nums.length - 1;

            while (j < k) {
                // 这里控制重复答案(之二),注意j最开始不需要跳过,和上面一样,故j>i+1
                if (j > i + 1 && nums[j - 1] == nums[j]) {
                    j++;
                } else if (nums[i] + nums[j] + nums[k] == 0) {
                    LinkedList<Integer> curr = new LinkedList<>(Arrays.asList(nums[i], nums[j], nums[k]));
                    result.add(curr);
                    break;
                } else if (nums[i] + nums[j] + nums[k] > 0) {
                    k--;
                } else {
                    j++;
                }
            }
        }
        return result;
    }


    /**
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> threeSum2(int[] nums) {
        List<List<Integer>> ans = new LinkedList<>();
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i-1]) continue;
            int j = i+1, k = nums.length-1;
            while (j < k) {
                if (j == i+1 || nums[j] != nums[j-1]) {
                    if (nums[i]+nums[j]+nums[k] == 0) { ans.add(Arrays.asList(nums[i], nums[j], nums[k])); j++; k--; }
                    else if (nums[i]+nums[j]+nums[k] < 0) j++;
                    else k--;
                }
                else j++;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Q15 q15 = new Q15();

        System.out.println(q15.threeSum(new int[]{-5,-5,-4,-3,-3,-2,-2,-1,-1,0,1,2,3,4,5}));
        System.out.println(q15.threeSum2(new int[]{-5,-5,-4,-3,-3,-2,-2,-1,-1,0,1,2,3,4,5}));
        System.out.println(q15.threeSum2(new int[]{-5,-4,-3,-2,-1,0,1,2,3,4,5}));
    }

}
